package com.jqb.jspcart.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jqb.jspcart.bean.Hardware;
import com.jqb.jspcart.service.impl.CartServiceImpl;

public class CartServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opt = request.getParameter("opt");
		String sort = request.getParameter("sort");
		String i = request.getParameter("id");
		String n = request.getParameter("num");
		int id=(i==null||"".equals(i))?0:Integer.parseInt(i);
		int num=(n==null||"".equals(n))?1:Integer.parseInt(n);
		
		CartServiceImpl cart = (CartServiceImpl)request.getSession().getAttribute("cart");
		if(cart==null){
			cart = CartServiceImpl.newInstance();
			request.getSession().setAttribute("cart",cart);
		}
		ArrayList<Hardware> goodsList = cart.getGoods();
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("sum", cart.getSum());
		request.setAttribute("size", cart.getSizeOfCart());
		
		//添加
		if("add".equals(opt)){
			cart.addGoods(id, num);
			goodsList = cart.getGoods();
			request.setAttribute("goodsList", goodsList);
			request.setAttribute("sum", cart.getSum());
			request.setAttribute("size", cart.getSizeOfCart());
			request.setAttribute("sort", sort);
			request.getRequestDispatcher("/hardwareServlet?opt=sort").forward(request,response);
		}
		//查看购物车
		if("show".equals(opt)){
			request.getRequestDispatcher("cart.jsp").forward(request, response);
		}
		//更新购物车
		if("update".equals(opt)){
			cart.updateGoods(id, num);
			goodsList = cart.getGoods();
			request.setAttribute("goodsList", goodsList);
			request.setAttribute("sum", cart.getSum());
			request.getRequestDispatcher("cart.jsp").forward(request, response);
		}
		//删除东西
		if("delete".equals(opt)){
			cart.delGoods(id);
			goodsList = cart.getGoods();
			request.setAttribute("goodsList", goodsList);
			request.setAttribute("sum", cart.getSum());
			request.setAttribute("size", cart.getSizeOfCart());
			request.getRequestDispatcher("cart.jsp").forward(request, response);
		}
	}
}
